#include <client.h>
#include <chat.h>

#include <config.h>

using namespace std;
using namespace Chat;

StateRet ClientRegisterUser(int sockfd)
{
    int ret{};
    /*声明用户需要的注册信息*/
    User    user{};
    char    buf[MAX_LINE]{};
    Message message{};

    /*获取用户输入*/
    printf("请输入注册用户名：\n");
    scanf("%s", user.userName);
    printf("user.UserName = %s\n", user.userName);

    printf("请输入注册用户密码：\n");
    scanf("%s", user.password);
    printf("user.password = %s\n", user.password);

    // 当前用户允许发言
    user.speak = Flag::YES;

    memset(buf, 0, MAX_LINE);
    memcpy(buf, &user, sizeof(user));
    send(sockfd, buf, sizeof(buf), 0);

    /*接收注册结果*/
    memset(buf, 0, MAX_LINE);
    recv(sockfd, buf, sizeof(buf), 0);
    message = Message{};
    memcpy(&message, buf, sizeof(buf));


    printf("%s\n", message.content);
    return message.msgRet;
}

StateRet ClientLoginUser(int sockfd)
{
    int                ret;
    struct sockaddr_in servaddr, local_addr;
    struct hostent*    host;
    socklen_t          len;
    /*声明用户登陆信息*/
    User    user{};
    char    buf[MAX_LINE];
    Message message{};
    /*获取用户输入*/
    printf("请输入用户名：\n");
    memset(user.userName, 0, sizeof(user.userName));
    scanf("%s", user.userName);
    printf("user.UserName = %s\n", user.userName);

    printf("请输入用户密码：\n");
    memset(user.password, 0, sizeof(user.password));
    scanf("%s", user.password);
    printf("user.password = %s\n", user.password);

    getsockname(sockfd, (struct sockaddr*)&local_addr, &len);
    user.userAddr = local_addr;

    printf("向服务器发送登录请求\n");

    /*发送用户登陆信息到服务器*/
    memset(buf, 0, MAX_LINE);
    memcpy(buf, &user, sizeof(user));
    send(sockfd, buf, sizeof(buf), 0);

    /*接收登陆结果*/
    memset(buf, 0, MAX_LINE);
    recv(sockfd, buf, sizeof(buf), 0);
    memset(&message, 0, sizeof(message));
    memcpy(&message, buf, sizeof(buf));

    printf("%s\n", message.content);

    /*如果登陆成功，则进入聊天界面*/
    if (message.msgRet == StateRet::SUCCESS) {
        ClientEnterChat(user, sockfd);
    }   // if
    return message.msgRet;
}
